<template>
  <div class="create-sp-campaign-wrap">
    <div class="left-wrap">
      <a-anchor ref="anchorRef" :change-hash="false" line-less :scroll-container="scrollbarRef" boundary="start">
        <a-anchor-link href="#campaign">广告活动</a-anchor-link>
        <a-anchor-link href="#products">广告组&商品</a-anchor-link>
        <a-anchor-link href="#target">投放</a-anchor-link>
        <a-anchor-link href="#negative">否定投放</a-anchor-link>
      </a-anchor>
    </div>

    <div class="right-wrap" v-if="showDetail">
      <a-scrollbar ref="scrollbarRef" outer-class="right-wrap-scrollbar">
        <div id="campaign" class="form-box">
          <CreateSpCampaignBase :campaignInfo="campaignInfo" />
        </div>
        <div id="products" class="form-box">
          <CreateSpProduct :darftInfo="darftInfo" :shop="advertStore.currentShop" :ref="refMap.productsRef" @change="changeEditAdgropInfo" />
        </div>
        <div id="target" class="form-box">
          <!-- 自动投放 -->
          <CreateSpAutoType :darftInfo="darftInfo" :shop="advertStore.currentShop" v-if="campaignInfo.targetingType === 'AUTO'" :ref="refMap.autoTypeRef" />
          <!-- 手动投放 -->
          <template v-if="campaignInfo.targetingType === 'MANUAL'">
            <CreateSpManualType :darftInfo="darftInfo" :shop="advertStore.currentShop" :ref="refMap.manualTypeRef" @change="changeEditAdgropInfo" />
            <!-- 关键词投放 -->
            <CreateSpKeyword :darftInfo="darftInfo" :shop="advertStore.currentShop" :products="editAdGroup.products" adType="SPONSORED_PRODUCTS" spKeywordRecommendationType="KEYWORDS_FOR_ASINS" :defaultTargetingBid="editAdGroup.defaultTargetingBid" v-if="editAdGroup.manualType === 'TARGETING_KEYWORD'" :ref="refMap.keywordRef" />
            <!-- 商品投放 -->
            <CreateSpProductTarge :darftInfo="darftInfo" :shop="advertStore.currentShop" :defaultTargetingBid="editAdGroup.defaultTargetingBid" v-if="editAdGroup.manualType === 'TARGETING_PRODUCT'" :ref="refMap.productTargeRef" />
          </template>
        </div>
        <div id="negative" class="form-box">
          <div class="edit-header">
            <p>否定投放</p>
          </div>
          <CreateSpNegKeyword :darftInfo="darftInfo" v-if="campaignInfo.targetingType === 'AUTO' || editAdGroup.manualType === 'TARGETING_KEYWORD'" style="margin-top: 20px" :ref="refMap.negKeywordRef" />
          <CreateSpNegProduct :darftInfo="darftInfo" v-if="campaignInfo.targetingType === 'AUTO' || editAdGroup.manualType === 'TARGETING_PRODUCT'" style="margin-top: 20px" :ref="refMap.negProductRef" />
        </div>
      </a-scrollbar>
    </div>
    <div class="footer-btn flex-c-end">
      <a-space>
        <a-button class="gray-outline" @click="showModel = true">关闭</a-button>
        <a-button type="primary" @click="createAd" :loading="submitLoading">新增广告组</a-button>
      </a-space>
    </div>
  </div>
  <a-modal v-model:visible="showModel" title-align="start" ok-text="退出" @ok="removeRoute">
    <template #title>
      <p class="flex-c">
        <icon-exclamation-circle style="margin-right: 5px" class="warn-icon warningColor" />
        <span>确认退出当前界面</span>
      </p>
    </template>
    <p>确认退出【创建广告组】界面</p>
    <p>注意：当前内容未保存，关闭后数据无法恢复！</p>
  </a-modal>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'CreateSpAdGroup',
  })
</script>
<script lang="ts" setup>
  import { defineComponent, ref, onActivated } from 'vue'
  import CreateSpCampaignBase from './components/createSpCampaignBase.vue'
  import CreateSpAutoType from './components/createSpAutoType.vue'
  import CreateSpManualType from './components/createSpManualType.vue'
  import CreateSpProduct from './components/createSpProduct.vue'
  import CreateSpNegKeyword from './components/createSpNegKeyword.vue'
  import CreateSpKeyword from './components/createSpKeyword.vue'
  import CreateSpProductTarge from './components/createSpProductTarge.vue'
  import CreateSpNegProduct from './components/createSpNegProduct.vue'
  import useAdvertStore from '@/store/modules/advert'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import { Message } from '@arco-design/web-vue'
  import { createAdGroup, getCampaignDetail } from '@/api/advert'
  import { useRouter, useRoute } from 'vue-router'
  import { parseJson } from '@/utils'
  onActivated(async () => {
    await getCampaignInfo()
    setDarftData()
  })
  const advertStore = useAdvertStore()
  const visitedRouteStore = useVisitedRouteStore()
  const scrollbarRef = ref()
  const anchorRef = ref()
  const router = useRouter()
  const route = useRoute()
  const showModel = ref(false)
  const campaignInfo = ref<any>({})
  const darftInfo = ref<any>({})
  const showDetail = ref<any>({})
  const submitLoading = ref(false)
  const refMap = {
    productsRef: ref(),
    autoTypeRef: ref(),
    manualTypeRef: ref(),
    negKeywordRef: ref(),
    negProductRef: ref(),
    keywordRef: ref(),
    productTargeRef: ref(),
  }
  const refElMap = {
    productsRef: 'products',
    autoTypeRef: 'target',
    manualTypeRef: 'target',
    negKeywordRef: 'negative',
    negProductRef: 'negative',
    keywordRef: 'target',
    productTargeRef: 'target',
  }
  // 当前广告组信息
  const editAdGroup = ref<any>({})

  // 获取广告活动详情
  async function getCampaignInfo() {
    const res: any = await getCampaignDetail({
      campaignId: advertStore.currentCampaign?.campaignId,
      shopId: advertStore.currentShop?.shopId,
    })
    campaignInfo.value = res?.data || {}
    campaignInfo.value.adjustmentAdsPlacementTopSearchPercentage = showBid('PLACEMENT_TOP')
    campaignInfo.value.adjustmentAdsPlacementProductDetailPercentage = showBid('PLACEMENT_PRODUCT_PAGE')
  }

  // 显示广告位竞价
  function showBid(key: string) {
    let dynamicBudgetPlacementBidding = parseJson(campaignInfo.value.dynamicBudgetPlacementBidding, [])
    return dynamicBudgetPlacementBidding.find((el: any) => el.placement === key)?.percentage
  }
  // 创建广告组
  async function createAd() {
    // 先校验
    let refArr = getRefModule()
    let errRef: Array<string> = []
    for (let refName of refArr) {
      let valid = await refMap[refName].value.validateData()
      if (!valid) {
        errRef.push(refName)
      }
    }
    if (errRef.length > 0) {
      let elId = refElMap[errRef[0]]
      changeMenu(elId)
      return
    }
    // 获取保存数据
    let saveInfo = getSavaData()
    submitLoading.value = true
    const res: any = await createAdGroup(saveInfo)
    submitLoading.value = false
    if (res?.data?.code === 'SUCCESS') {
      Message.success('创建广告组成功')
      removeRoute()
    } else {
      Message.error({
        content: res?.data?.errorMsg,
        duration: 4000,
      })
      let _data = res?.data?.data || {}
      advertStore.changeDarftInfo(_data)
      setDarftData()
    }
  }
  function removeRoute() {
    router.push('/advert/campaign/campaignDetail')
    visitedRouteStore.removeVisitedRoute(route)
    advertStore.restorEeditSpCampaign()
  }
  // 获取保存数据
  function getSavaData() {
    let saveInfo: any = {
      adType: 'SPONSORED_PRODUCTS',
      targeting: campaignInfo.value.targetingType,
      shopId: campaignInfo.value.shopId,
      campaignId: campaignInfo.value.campaignId,
      bidStrategy: campaignInfo.value.dynamicBudgetStrategy,
      adjustmentAdsPlacementTopSearchPercentage: campaignInfo.value.adjustmentAdsPlacementTopSearchPercentage,
      adjustmentAdsPlacementProductDetailPercentage: campaignInfo.value.adjustmentAdsPlacementProductDetailPercentage,
    }
    if (darftInfo.value?.draftId) {
      saveInfo.campaignDraftId = darftInfo.value.draftId
    }
    let refArr = getRefModule()
    refArr.forEach((refName) => {
      let refVal = refMap[refName].value.setCreateData() || {}
      saveInfo = { ...saveInfo, ...refVal }
    })
    return saveInfo
  }
  function setDarftData() {
    showDetail.value = false
    if (!advertStore.darftInfo?.id) {
      darftInfo.value = {}
    } else {
      let configuration = parseJson(advertStore.darftInfo?.configuration, {})
      let defaultVal = {
        draftId: advertStore.darftInfo?.id,
        handlerFlow: advertStore.darftInfo?.handlerFlow,
      }
      darftInfo.value = { ...configuration, ...defaultVal }
    }
    setTimeout(() => {
      showDetail.value = true
    }, 10)
  }
  //移动到指定位置
  async function changeMenu(elId: string) {
    let el = document.querySelector(`#${elId}`) as HTMLElement
    let scrollEl = document.querySelector(`.arco-scrollbar-container`) as HTMLElement
    scrollEl.scrollTop = el?.offsetTop || 0
  }
  // 获取对应模块
  function getRefModule() {
    let refArr = ['productsRef']
    if (campaignInfo.value.targetingType === 'AUTO') {
      // 自动投放显示-自动投放竞价、否定关键词、否定商品
      refArr = [...refArr, ...['autoTypeRef', 'negKeywordRef', 'negProductRef']]
    } else if (editAdGroup.value.manualType === 'TARGETING_KEYWORD') {
      // 手动投放&关键词投放-手动投放竞价、关键词投放、否定关键字投放
      refArr = [...refArr, ...['manualTypeRef', 'keywordRef', 'negKeywordRef']]
    } else if (editAdGroup.value.manualType === 'TARGETING_PRODUCT') {
      // 手动投放&商品投放-手动投放竞价、商品投放、否定商品投放
      refArr = [...refArr, ...['manualTypeRef', 'productTargeRef', 'negProductRef']]
    }
    return refArr
  }
  function changeEditAdgropInfo(key: string, val: any) {
    editAdGroup.value[key] = val
  }
</script>
<style lang="less" scoped>
  .create-sp-campaign-wrap {
    position: relative;
    height: 100%;
    overflow: hidden;
    padding-left: 200px;
    padding-bottom: 52px;
  }
  .left-wrap {
    background-color: #fff;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    width: 190px;
    padding: 20px 10px;
  }
  .right-wrap {
    width: 100%;
    background-color: #fff;
  }
  .form-box {
    margin-bottom: 20px;
    width: 100%;
    padding: 0 20px;
  }
  .footer-btn {
    position: absolute;
    bottom: 0;
    left: 200px;
    box-shadow: 0 -2px 4px 0 rgba(0, 0, 0, 0.1);
    right: 0;
    padding: 10px 20px;
    background-color: #fff;
  }
  .edit-header {
    background-color: var(--color-fill-2) !important;
    border-left: 2px solid rgb(var(--primary-6));
    line-height: 32px;
    font-size: 16px;
    padding-left: 20px;
  }
  .right-wrap-scrollbar {
    height: calc(100vh - @menuHeight - 52px);
    overflow: auto;
  }
</style>
